package cn.finyzq.ss.games.web.ws;

import cn.finyzq.ss.games.service.RoomService;
import cn.finyzq.ss.games.utils.ResultCode;
import cn.finyzq.ss.games.vo.ResultBean;
import cn.finyzq.ss.games.vo.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Create Time: 2018年08月05日 14:25
 *
 * @author fin
 */
@Component
public class RoomSocket extends TextWebSocketHandler {

    /** logger */
    private Logger logger = LogManager.getLogger(RoomSocket.class);
    
    @Autowired
    private RoomService roomService;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info(session.getAttributes());

        User user = (User) session.getAttributes().get("_user");
        // 添加用户的websocket数据
        roomService.addUserWsSession(user.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JSONObject json = JSON.parseObject(message.getPayload());
        logger.info(json);
        if(json.getString("roomNo") == null){
            ResultBean resultBean = new ResultBean(ResultCode.WS_ROOM_BLANK, "房间号为空");
            session.sendMessage(new TextMessage(resultBean.toString()));

        }
        if(json.getString("msgType") == null){
            ResultBean resultBean = new ResultBean(ResultCode.WS_MSG_TYPE_BLANK, "消息类型为空");
            session.sendMessage(new TextMessage(resultBean.toString()));
        }
        roomService.excuteWebSocketMessage(json, session);

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.info("close");
    }
}
